import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.smartcardio.CardException;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import ruptela.*;
/**
 *
 * @author Bartlomiej Zeslawski, Globtrak Polska Sp. z o. o.
 */
public class SmartCardTest extends javax.swing.JApplet {

    /**
     * Initializes the applet SmartCardTest
     */
    @Override
    public void init() {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SmartCardTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SmartCardTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SmartCardTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SmartCardTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the applet */
        try {
            java.awt.EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    initComponents();
                    terminalList.setCellRenderer(new TerminalListCellRenderer());
                }
            });
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * This method is called from within the init() method to initialize the
     * form. WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        getTerminalsBtn = new javax.swing.JButton();
        terminalListScrollPane = new javax.swing.JScrollPane();
        terminalList = new javax.swing.JList();
        getParamBtn = new javax.swing.JButton();
        testConnectionBtn = new javax.swing.JButton();
        testServerConnectionBtn = new javax.swing.JButton();

        getTerminalsBtn.setText("Get terminals");
        getTerminalsBtn.setToolTipText("");
        getTerminalsBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                getTerminalsBtnActionPerformed(evt);
            }
        });

        terminalList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        terminalListScrollPane.setViewportView(terminalList);

        getParamBtn.setText("Get parameter");
        getParamBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                getParamBtnActionPerformed(evt);
            }
        });

        testConnectionBtn.setText("Test reader connection");
        testConnectionBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                testConnectionBtnActionPerformed(evt);
            }
        });

        testServerConnectionBtn.setText("Test server connection");
        testServerConnectionBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                testServerConnectionBtnActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(terminalListScrollPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(getTerminalsBtn)
                                .addGap(26, 26, 26)
                                .addComponent(getParamBtn))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(testConnectionBtn)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(testServerConnectionBtn)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(getTerminalsBtn)
                    .addComponent(getParamBtn))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(terminalListScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(testConnectionBtn)
                    .addComponent(testServerConnectionBtn))
                .addContainerGap(101, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void getTerminalsBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_getTerminalsBtnActionPerformed

        Reader reader = new Reader();
        List<TerminalCard> tcs = reader.getList();
        if (tcs.size() > 0) {
            DefaultListModel listModel = new DefaultListModel();
            for (int i = 0; i < tcs.size(); ++i) {
                TerminalCard tc = tcs.get(i);
                listModel.addElement(tc);
            }
            terminalList.setModel(listModel);
        } else {
            JOptionPane.showMessageDialog(null, "Can't find any card readers or they don't have tacho cards inserted");
        }
    }//GEN-LAST:event_getTerminalsBtnActionPerformed

    private void getParamBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_getParamBtnActionPerformed
        String tmp = getParameter("msg");
        if (tmp == null) JOptionPane.showMessageDialog(null, "Parameter \"msg\" not set!");
        else JOptionPane.showMessageDialog(null, tmp);
    }//GEN-LAST:event_getParamBtnActionPerformed

    private void testConnectionBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_testConnectionBtnActionPerformed
        TerminalCard tc = (TerminalCard) terminalList.getSelectedValue();
        if (tc == null) {
             JOptionPane.showMessageDialog(null, "Please select terminal first");
        } else {
            try {
                tc.connect();
                if (tc.isConnected())  {
                    JOptionPane.showMessageDialog(null, "Connection OK");
                    byte[] atr = tc.getATR();
                    StringBuilder sb = new StringBuilder();
                    for (byte b : atr) { sb.append(String.format("%02X ", b)); }
                    JOptionPane.showMessageDialog(null, "ATR: " + sb.toString());
                    tc.disconnect();
                }
                else JOptionPane.showMessageDialog(null, "Connection NOT OK");
            } catch (CardException ex) {
                JOptionPane.showMessageDialog(null, "Error connecting terminal: " + ex.getMessage());
            }
        }
    }//GEN-LAST:event_testConnectionBtnActionPerformed

    private void testServerConnectionBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_testServerConnectionBtnActionPerformed
        Socket clientSocket;
        PrintWriter output;
        BufferedReader input;
        try {
            clientSocket = new Socket("127.0.0.1", 10010);
            clientSocket.setSoTimeout(25000);
            output = new PrintWriter(clientSocket.getOutputStream(), true);
            input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            boolean running = true;
            try {
                while(running) {
                    output.println("PING");
                    String response = input.readLine();
                    if ("PONG".equals(response)) {
                        JOptionPane.showMessageDialog(null, "Communication OK", "Success", JOptionPane.INFORMATION_MESSAGE);
                        running = false;
                    }
                }
            } catch (SocketTimeoutException ex) {
                running = false;
                JOptionPane.showMessageDialog(null, "Timeout", "WARNING", JOptionPane.WARNING_MESSAGE);
            }
            input.close();
            output.close();
            clientSocket.close();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "Error during server communication: " + e.getMessage(), "Exception occured", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_testServerConnectionBtnActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton getParamBtn;
    private javax.swing.JButton getTerminalsBtn;
    private javax.swing.JList terminalList;
    private javax.swing.JScrollPane terminalListScrollPane;
    private javax.swing.JButton testConnectionBtn;
    private javax.swing.JButton testServerConnectionBtn;
    // End of variables declaration//GEN-END:variables
}
